package cn.quevo.core.lang;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json操作工具类
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2018-03-09 16:17:12
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @return
 */
public class JSONUtils {
    private final static Logger log = LoggerFactory.getLogger(JSONUtils.class);
    private static ObjectMapper objectMapper;

    /**
     * 获取ObjectMapper
     *
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 16:17:33
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    private static ObjectMapper getObjectMapper() {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        return objectMapper;
    }

    /**
     * 将Object对象转换成Json字符串
     *
     * @param obj
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 16:17:38
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static String format(Object obj) {
        if (StringUtils.isBlank(obj)) {
            return "";
        }
        log.debug(obj.getClass().getName());
        try {
            return getObjectMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    /**
     * 将json字符串转换成对象
     *
     * @param json
     * @param valueType
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 16:17:44
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static <T> T parse(String json, Class<T> valueType) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        log.debug(json);
        try {
            return getObjectMapper().readValue(json, valueType);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
